package com.dlg.exchange.gateway;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alipay.sofa.rpc.config.ProviderConfig;
import com.alipay.sofa.rpc.config.ServerConfig;
import com.dlg.common.fetchsurv.IFetchService;
import com.dlg.exchange.gateway.container.OrderCmdContainer;
import com.dlg.exchange.gateway.handler.ConnHandler;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@Log4j2
@SpringBootApplication(exclude= {DruidDataSourceAutoConfigure.class, DataSourceAutoConfiguration.class})
public class GatewayApplication implements CommandLineRunner {
    @Autowired
    OrderCmdContainer orderCmdContainer;
    @Autowired
    Vertx vertx;
    @Autowired
    ConnHandler connHandler;
    //排队机通信Provider端口
    @Value("${fetchServPort}")
    private String fetchServPort;
    @Value("${recvPort}")
    private String recvPort;

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        initRecv();
        initFetchServ();
    }

    private void initRecv() {
        NetServer server = vertx.createNetServer();
        server.connectHandler(connHandler);
        server.listen(Integer.parseInt(recvPort), res -> {
            if (res.succeeded()) {
                log.info("gateway startup success at port : {}", recvPort);
            } else {
                log.error("gateway startup fail");
            }
        });
    }

    private void initFetchServ() {
        ServerConfig rpcConfig = new ServerConfig()
                .setPort(Integer.parseInt(fetchServPort))
                .setProtocol("bolt");

        //implement IFetchService
        ProviderConfig<IFetchService> providerConfig = new ProviderConfig<IFetchService>()
                .setInterfaceId(IFetchService.class.getName())
                .setRef(() -> orderCmdContainer.getAll())
                .setServer(rpcConfig);
        providerConfig.export();

        log.info("gateway startup fetchServ success at port : {}", fetchServPort);

    }
}